package tech.yozo.bamboo.ui.reading;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;

import android.annotation.SuppressLint;
import android.graphics.RectF;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.google.android.material.card.MaterialCardView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import tech.yozo.bamboo.R;
import tech.yozo.bamboo.databinding.FragmentReadingBinding;
import tech.yozo.bamboo.model.DictWord;
import tech.yozo.bamboo.model.SelectedText;
import tech.yozo.bamboo.ui.style.WordSpan;
import tech.yozo.bamboo.utils.MimeType;

public class ReadingFragment extends Fragment implements WordSpan.OnClickListener {

    private ReadingViewModel model;
    private FragmentReadingBinding binding;

    private int width = 0;
    private boolean translateOn = true;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            String type = bundle.getString("type");
            if (type != null) {
                switch (type) {
                    case MimeType.MIME_TYPE_PNG:
                    case MimeType.MIME_TYPE_JPG:
                        getChildFragmentManager().beginTransaction()
                                .replace(R.id.content_fragment_container, ReadImageFragment.newInstance(null, null))
                                .commit();
                        break;
                    case MimeType.MIME_TYPE_EPUB:
                        getChildFragmentManager().beginTransaction()
                                .replace(R.id.content_fragment_container, ReadBookFragment.newInstance(null, null))
                                .commit();
                        break;
                    default:
                        // 不支持
                }
            }
        }

        // 绑定数据
        model =  new ViewModelProvider(requireActivity()).get(ReadingViewModel.class);
        LiveData<SelectedText> selectedText = model.getSelectedText();
        selectedText.observe(getViewLifecycleOwner(), this::updateTextCard);

        LiveData<String> transText = model.getTransText();
        transText.observe(getViewLifecycleOwner(), this::updateTranslatedCard);

        LiveData<DictWord> dictWord = model.getDictWord();
        dictWord.observe(getViewLifecycleOwner(), this::updateDictCard);

        // 绑定视图
        binding = FragmentReadingBinding.inflate(inflater, container, false);
        ToggleButton translateButton = binding.translateButton;
        translateButton.setOnCheckedChangeListener(this::onCheckedTranslateButton);

        ImageButton speakButton = binding.speakButton;
        speakButton.setOnClickListener(v -> model.doTTS(binding.selectedTextView.getText().toString()));

        ImageButton wordSpeakButton = binding.wordSpeakButton;
        wordSpeakButton.setOnClickListener(v -> model.doTTS(binding.wordView.getText().toString()));

        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        binding.selectedView.setVisibility(View.INVISIBLE);
        binding.translatedView.setVisibility(View.INVISIBLE);
        binding.dictView.setVisibility(View.INVISIBLE);

        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        model.clearState();
        super.onDestroyView();
    }

    private void onCheckedTranslateButton(CompoundButton button, boolean isChecked) {
        MaterialCardView translatedView = binding.translatedView;
        TextView selectedTextView = binding.selectedTextView;
        if (isChecked) {
            translateOn = true;
            // 翻译
            model.doTranslate(selectedTextView.getText().toString());
        } else {
            translateOn = false;
            // 动画
            Animation animation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,Animation.RELATIVE_TO_SELF, 0.97f, Animation.RELATIVE_TO_SELF, 1.0f);
            animation.setDuration(100);
            translatedView.startAnimation(animation);
            translatedView.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 更新词典卡片
     * @param dictWord 单词释义
     */
    private void updateDictCard(DictWord dictWord) {
        if (dictWord == null) {
            return;
        }

        if (dictWord.word == null || dictWord.word.isEmpty()) {
            //TODO 本地词典查不到，到网络词典查
            binding.wordView.setText("本地词典没找到该词汇");
            binding.wordPhoneticView.setText("");
            binding.wordTranslationView.setText("");
            binding.wordTagView.setText("");
            binding.wordExchangeView.setText("");
        } else {
            binding.wordView.setText(dictWord.word);
            binding.wordPhoneticView.setText(String.format("[%s]", dictWord.phonetic));
            binding.wordTranslationView.setText(dictWord.translation);
            binding.wordTagView.setText(dictWord.tag);
            binding.wordExchangeView.setText(dictWord.exchange);
        }

        MaterialCardView dictView = binding.dictView;
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) dictView.getLayoutParams();
        layoutParams.width = width;
        dictView.setLayoutParams(layoutParams);
        dictView.setVisibility(View.VISIBLE);
        dictView.requestLayout();

        // 动画
        Animation animation = new ScaleAnimation(0.1f, 1.0f, 0.1f, 1.0f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.0f);
        animation.setDuration(100);
        dictView.startAnimation(animation);
    }

    /**
     * 更新翻译卡片
     * @param translation 翻译文本
     */
    private void updateTranslatedCard(String translation) {
        if (translation == null) {
            return;
        }

        String style = "译文：" + translation;
        binding.translatedTextView.setText(style);


        MaterialCardView translatedView = binding.translatedView;
        // 更新翻译卡片并展示
        ConstraintLayout.LayoutParams translateViewLayoutParams = (ConstraintLayout.LayoutParams) translatedView.getLayoutParams();
        translateViewLayoutParams.width = width;
        translatedView.setLayoutParams(translateViewLayoutParams);
        translatedView.setVisibility(View.VISIBLE);
        translatedView.requestLayout();

        // 动画
        Animation animation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.97f, Animation.RELATIVE_TO_SELF, 1.0f);
        animation.setDuration(100);
        translatedView.startAnimation(animation);
    }

    /**
     * 更新文本卡片并展示
     * @param text 文本
     */
    private void updateTextCard(SelectedText text) {
        if (text == null) {
            return;
        }
        if (text.text != null) {
            // 翻译
            if (translateOn) {
                model.doTranslate(text.text);
            }

            MaterialCardView selectedView = binding.selectedView;
            TextView selectedTextView = binding.selectedTextView;
            FrameLayout layout = binding.contentFragmentContainer;
            // 设置原始文本
            selectedTextView.setText(spanEveryWord(text.text));
            selectedTextView.setMovementMethod(LinkMovementMethod.getInstance());

            ConstraintLayout.LayoutParams selectedViewLayoutParams = (ConstraintLayout.LayoutParams) selectedView.getLayoutParams();

            RectF rect = text.rect;
            // 计算文本卡片layout
            int imageHalfWidth = layout.getWidth() / 2;
            if (rect.width() < (float) imageHalfWidth) {
                width = imageHalfWidth;
            } else if (layout.getRight() - rect.right < 90) {
                width = (int) rect.width();
            } else {
                width = (int) (rect.width() + 90);
            }
            selectedViewLayoutParams.width = width;
            selectedView.setLayoutParams(selectedViewLayoutParams);
            selectedView.requestLayout();

            int d = (int) (rect.left + width - layout.getRight());
            if (d > 0) {
                selectedViewLayoutParams.leftMargin = (int) (rect.left - d - 10);
            } else {
                selectedViewLayoutParams.leftMargin = (int) (rect.left - 10);
            }
            if (selectedViewLayoutParams.height > rect.height()) {
                selectedViewLayoutParams.topMargin = (int) (rect.top - (selectedViewLayoutParams.height - rect.height()) / 2 - 10);
            } else {
                selectedViewLayoutParams.topMargin = (int) rect.top - 10;
            }
            selectedView.setLayoutParams(selectedViewLayoutParams);
            selectedView.setVisibility(View.VISIBLE);
            selectedView.requestLayout();

            // 动画
            Animation animation = new ScaleAnimation(0.5f, 1.0f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(100);
            selectedView.startAnimation(animation);
        } else {
            // 动画
            Animation animation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setDuration(100);
            if (binding.selectedView.getVisibility() == View.VISIBLE) {
                binding.selectedView.setVisibility(View.INVISIBLE);
                binding.selectedView.startAnimation(animation);
            }
            if (binding.translatedView.getVisibility() == View.VISIBLE) {
                binding.translatedView.setVisibility(View.INVISIBLE);
                binding.translatedView.startAnimation(animation);
            }
            if (binding.dictView.getVisibility() == View.VISIBLE) {
                binding.dictView.setVisibility(View.INVISIBLE);
                binding.dictView.startAnimation(animation);
            }
        }
    }

    /**
     * 将文本拆分成单词展示
     *
     * @param text 文本
     * @return 拆分后的富文本
     */
    private SpannableStringBuilder spanEveryWord(String text) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);

        Pattern pattern = Pattern.compile("\\b\\w+\\b");
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            WordSpan wordSpan = new WordSpan(text.substring(matcher.start(), matcher.end()));
            wordSpan.setOnClickListener(this);
            builder.setSpan(wordSpan, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        return builder;
    }

    /**
     * 将文本拆分成单词展示
     *
     * @param text 文本
     * @return 拆分后的富文本
     */
    @Deprecated
    private SpannableStringBuilder spanEveryWord(String text, int n) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);

        int index = text.indexOf(" ");
        int start = 0;
        do {
            builder.setSpan(new WordSpan(text.substring(start, index)), start, index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = index + 1;
            // 从当前位置之后继续查找
            index = text.indexOf(" ", index + 1);
        } while (index != -1);

        builder.setSpan(new WordSpan(text.substring(start)), start, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

    /**
     * 单词被点击时
     *
     * @param wordSpan 被点击的单词
     */
    @Override
    public void onClicked(WordSpan wordSpan) {
        model.doDict(wordSpan.getWord());
    }
}